<template>
  <div class="app-container">
    <el-container v-loading="changeLoading"
                  element-loading-text="切换租户中..."
                  element-loading-spinner="el-icon-loading"
    >
      <el-header class="filter-container">
        <el-select v-model="condition.organize" placeholder="组织结构" class="filter-item" :clearable="true"
                   :disabled="isDisable" @change="changeTenant"
                   @clear="()=>{condition.organize=''}">
          <el-option
            v-for="item in organizeList"
            :key="item.id"
            :label="item.tenantName"
            :value="item.tenantId"
            :disabled="item.active==0">
          </el-option>
        </el-select>
        <el-input v-model="condition.account" placeholder="请输入用户名" style="width: 200px;"
                  class="filter-item"></el-input>

        <el-button type="primary" icon="el-icon-search" @click="onSearch" style="width: 90px;" class="filter-item">搜索
        </el-button>
        <el-button type="primary" icon="el-icon-plus" @click="onCreate(0)" class="filter-item">新建</el-button>
      </el-header>
      <el-main>
        <el-table :data="temperList" style="width: 100%;margin-top:30px;" border v-loading="listLoading">
          <el-table-column align="center" label="ID" width="120">
            <template slot-scope="scope">
              {{ scope.row.id }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="账号" width="120">
            <template slot-scope="scope">
              {{ scope.row.account }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="密码" width="120">
            <template slot-scope="scope">
              {{ scope.row.passwd }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="姓名" width="120">
            <template slot-scope="scope">
              {{ scope.row.realname }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="组织结构" width="120">
            <template slot-scope="scope">
              {{

                findObjByProp('tenantId', scope.row.organize, organizeList).tenantName

              }}
            </template>
          </el-table-column>

          <el-table-column align="center" label="角色" width="120">
            <template slot-scope="scope">
              {{
                findObjByProp('kcode', scope.row.role, roleList).name
              }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="联系方式" width="120">
            <template slot-scope="scope">
              {{ scope.row.tel }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="权限" width="120">
            <template slot-scope="scope">
              {{ scope.row.routes }}
            </template>
          </el-table-column>

          <!--          <el-table-column align="header-center" label="描述">-->
          <!--            <template slot-scope="scope">-->
          <!--              {{ scope.row.description }}-->
          <!--            </template>-->
          <!--          </el-table-column>-->
          <el-table-column align="center" label="状态" width="120">
            <template slot-scope="scope">
              <el-switch
                v-model="scope.row.alive"
                active-color="#13ce66"
                :active-value="1"
                :inactive-value="0"
                @change="changeAlive(scope)"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column align="center" label=操作>
            <template slot-scope="scope">
              <el-button type="primary" size="small" @click="handleEdit(scope)">编辑</el-button>
              <el-button type="danger" size="small" @click="handleDelete(scope)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <!--        <el-pagination-->
        <!--          style="margin-top: 20px"-->
        <!--          @size-change="handleSizeChange"-->
        <!--          @current-change="handleCurrentChange"-->
        <!--          :current-page="1"-->
        <!--          :page-sizes="[50, 60, 70, 80]"-->
        <!--          :page-size="100"-->
        <!--          layout="total, sizes, prev, pager, next, jumper"-->
        <!--          :total="temperList.length">-->
        <!--        </el-pagination>-->

        <!--      创建用户面板-->
        <el-dialog
          :title="dialogTitle[dialogType]"
          :visible.sync="dialogVisible"
          :close-on-click-modal=false
          top="5vh">

          <el-form
            ref="formConsumer"
            :close="closeDialog"
            :model="temper"
            :rules="rules"
            label-width="100px"
            style="width: 80%; margin-left:50px;">
            <el-form-item label="账号：" prop="account">
              <el-input v-model.trim="temper.account"
                        :disabled="dialogType=='1'?true:false"
              ></el-input>
              <span class="underInputWords">字母、数字、下划线</span>
            </el-form-item>
            <el-form-item label="密码：" prop="passwd">
              <el-input v-model.trim="temper.passwd"></el-input>
            </el-form-item>
            <el-form-item label="姓名：">
              <el-input v-model="temper.realname"></el-input>
            </el-form-item>
            <el-form-item label="电话/手机：" prop="tel">
              <el-input v-model.number="temper.tel" maxlength="11"></el-input>
            </el-form-item>

            <el-form-item label="角色：">
              <el-select v-model="temper.role" placeholder="请选择角色" @change="handleSelectChange">
<!--                :disabled="user_role=='RA0001'?false:true"-->
                <el-option v-for="(item,index) in roleList"
                           :label="item.name"
                           :value="item.kcode">
                </el-option>
              </el-select>
            </el-form-item>

            <el-form-item label="组织结构：" prop="order">
              <el-select v-model="temper.organize" placeholder="请选择组织结构" :disabled="this.condition.organize==''?false:true" @change="changeTenant">
                <el-option v-for="(item,index) in organizeList"
                           :label="item.tenantName"
                           :value="item.tenantId"
                           :disabled="item.active==0">
                </el-option>
              </el-select>
            </el-form-item>

            <!--            <el-form-item label="描述：" prop="describe">-->
            <!--              &lt;!&ndash;              <el-input v-model.number="defaultOrder.describe"></el-input>&ndash;&gt;-->
            <!--              <el-input-->
            <!--                type="textarea"-->
            <!--                :rows="2"-->
            <!--                placeholder="请输入内容"-->
            <!--                v-model="temper.description">-->
            <!--              </el-input>-->
            <!--            </el-form-item>-->

            <el-form-item label="权限：">
              <el-tree
                ref="tree"
                :check-strictly="checkStrictly"
                :data="routesData"
                :props="defaultProps"
                show-checkbox
                node-key="id"
                class="permission-tree"
              />
            </el-form-item>


            <el-form-item>
              <div style="text-align:right;">
                <el-button type="danger" @click="cancelConsumer">取消</el-button>
                <el-button type="primary" @click="confirmConsumer(dialogType)">确认</el-button>
              </div>
            </el-form-item>
          </el-form>

        </el-dialog>
      </el-main>

    </el-container>
  </div>
</template>

<script>
import { deepClone } from '@/utils'
import {
  deleteConsumer,
  addConsumer,
  getConsumers,
  updateConsumer,
  addOrder,
  updateOrder,
  getConsumersCondition
} from '@/api/basicmgt'
import { getRoles, getRoutes } from '@/api/role'
import path from 'path'
import { getTenants } from '@/api/tenant'
import { arrMerge, findObjByProp } from '@/utils/utilc'
import { Message } from 'element-ui'
import { routerListFun } from '@/router/Jurisdiction'
import { getDynamicRoutes } from '@/router'
import { mapGetters } from 'vuex'
import { addConsumerHXY } from '@/api/hxy'

const defaultRole = {
  id: '',
  account: '',
  passwd: '',
  role: '',
  realname: '',
  alive: '1',//状态
  tel: '',
  organize: '',
  // description: '',
  routes: []
}

export default {
  name: 'users',

  data() {
    return {
      rules: {
        account: [{ required: true, message: '不能为空', trigger: 'blur' }],
        passwd: [{ required: true, message: '不能为空', trigger: 'blur' }],
        tel: [{ required: true, message: '请输入正确格式', trigger: 'blur' }],
        role: [{ required: true, message: '不能为空', trigger: 'blur' }]

      },
      input_toolbar: '',
      dialogTitle: ['创建', '编辑'],
      temper: Object.assign({}, defaultRole),
      routes: [],
      temperList: [],
      roleList: [],
      // organizeList:this.$global.ORGANIZELIST,
      organizeList: [],
      dialogVisible: false,
      dialogType: '0',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      listLoading: false,

      condition: {
        account: '',
        organize: ''
      },

      changeLoading: false,
      hxy_structure: 0

    }
  },

  computed: {
    routesData() {
      return this.routes
    },
    ...mapGetters([
      'name',
      'avatar',
      'user_organize',
      'user_role',
      'user_routes'
    ]),

    isDisable: {
      get() {
        return this.user_role == 'RA0003' ? true : false
      },
      set(val) {
      }
    }
  },

  created() {
    // Mock: get all routes and roles list from server
    if (this.user_role == 'RA0003') {
      this.condition.organize = this.user_organize
    }
    this.getRoutes()
    this.getConsumers()
    this.getOrganize()

  },

  methods: {

    findObjByProp(pname, value, array) {
      return findObjByProp(pname, value, array)
    },

    onSearch() {

      if (this.condition.organize != null && this.condition.organize != '') {

        this.getConsumers()

      } else {

        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
      }

    },

    async changeTenant(tenant) {


      if (tenant != null && tenant != '') {

        let tenantName = findObjByProp('tenantId', tenant, this.organizeList).tenantName
        console.log('切换租户：' + tenant+" "+tenantName)

        this.changeLoading = true
        await this.$global.CHANGE_TENANT(tenant).then(//华栖云租户登录
          (res) => {

            this.temper.organize = tenant

            // if(this.condition.organize!=null&&this.condition.organize!=''){
            // let tenantName = findObjByProp('tenantId',this.condition.organize, this.organizeList).tenantName
            this.$global.GET_HXY_STRUCTURE(tenantName).then(res=>{
              this.hxy_structure = res
            console.log('组织结构：' + JSON.stringify(this.hxy_structure))
            })
            // }
            // console.log('changeTenant=true='+res)
            this.changeLoading = false
            this.$notify({
              title: 'Success',
              dangerouslyUseHTMLString: true,
              message: '【'+tenantName+'】切换成功!',
              type: 'success',
              duration: 1500

            })
          },
          () => {
            this.condition.organize = ''
            this.temper.organize = ''
            this.changeLoading = false
            this.$notify({
              title: 'Error',
              dangerouslyUseHTMLString: true,
              message: '【'+tenantName+'】切换失败!',
              type: 'error',
              duration: 1500

            })
          }
        ).catch(error => {
          this.condition.organize = ''
          this.temper.organize = ''

          this.changeLoading = false
          this.$notify({
            title: 'Error',
            dangerouslyUseHTMLString: true,
            message: '【'+tenantName+'】切换异常!',
            type: 'error',
            duration: 1500

          })
        })
        this.temperList = []
      }

    },


    async onCreate(type) {



      if(this.condition.organize==null||this.condition.organize==''){
        Message({
          message: '组织结构不能为空',
          type: 'error',
          duration: 1000
        })
        return false
      //   let tenantName = findObjByProp('tenantId',this.condition.organize, this.organizeList).tenantName
      //   this.hxy_structure = await this.$global.GET_HXY_STRUCTURE(tenantName)
      //   console.log("组织结构："+JSON.stringify(this.hxy_structure))
      }

      this.dialogType = type + ''
      this.dialogVisible = true
      this.temper = Object.assign({}, defaultRole)
      if (this.user_role == 'RA0003') {
        this.temper.organize = this.user_organize
        this.temper.role = this.user_role
      }else{
        this.temper.organize = this.condition.organize
      }

    },

    getRoutesArr(kcode) {

      let route = findObjByProp('kcode', kcode, this.roleList).routes
      let arr = route.split(',')
      arr.forEach(function(value, index, arr) {
        arr[index] = parseInt(value)
      })

      return arr

    },

    async getRoutes() {
      // const roles = await getRoles();
      // this.roleList = roles.data
      // await this.$global.getROLE_ID_HXY("RA0001")
      this.roleList = await this.$global.ROLE()

      //需要展示当前登录账号的角色及下辖角色
      // let roleListTemp = await this.$global.ROLE()
      // if( roleListTemp.length>0){
      //
      // }



      const res = await getRoutes()
      this.serviceRoutes = res.data
      this.routes = this.generateRoutes(res.data)
    },

    async getConsumers() {
      this.listLoading = true
      if (this.condition.organize != null && this.condition.organize != '') {
        const res = await getConsumersCondition(this.condition)
        this.temperList = res.data
      }

      setTimeout(() => {
        this.listLoading = false
      }, 1.5 * 1000)
      // console.log("list="+JSON.stringify(this.temperList))
    },

    async getOrganize() {
      const res = await getTenants()
      this.organizeList = res.data
    },

    cancelConsumer() {
      this.dialogVisible = false
        this.$nextTick(() => {
          this.$refs['formConsumer'].clearValidate() // 只清除验证
        })
    },
    closeDialog(){
      this.cancelConsumer()
    },

    async confirmConsumer(type) {

      let checkedKeys = this.$refs.tree.getCheckedKeys()
      let checkedHalfKeys = this.$refs.tree.getHalfCheckedKeys()
      const checkAllKeys = arrMerge(checkedKeys, checkedHalfKeys)
      this.temper.routes = checkAllKeys.toString()

      if (type == 0) {//创建

        // this.temper.routes = this.temper.routes.toString()

        // let role_ids=[]
        // let structure_ids=[]
        // role_ids.push(await this.$global.getROLE_ID_HXY(this.temper.role))
        // structure_ids.push(this.hxy_structure)
        // let role_ids = await this.$global.getROLE_ID_HXY(this.temper.role)
        let role_ids = findObjByProp('kcode', this.temper.role, this.roleList).name

        let structure_ids = this.hxy_structure

        let hxy_data = {
          role_name: role_ids,
          structure_name: structure_ids,//
          account: this.temper.account,
          // phone:this.temper.tel+"",
          realname: this.temper.realname,
          password: this.temper.passwd,
          bindcode: this.temper.organize
          // pay_status:1,
          // expire:1,
          // iptv_bindcode:"1",
        }

        // console.log("hxy_data="+JSON.stringify(hxy_data))

        const { code, data, msg } = await addConsumer(this.temper)
        const {} = await addConsumerHXY(hxy_data)

        if (code == '20000') {
          this.temper.id = data.id
          this.temperList.push(this.temper)
        } else {
          new Error(data || 'Error')
        }

      } else {//edit
        const { code, data, msg } = await updateConsumer(this.temper.id, this.temper)

        if (code == '20000') {
          for (let index = 0; index < this.temperList.length; index++) {
            if (this.temperList[index].id === this.temper.id) {
              this.temperList.splice(index, 1, Object.assign({}, this.temper))
              break
            }
          }
        } else {
          new Error('发生了错误，请稍后再试' || 'Error')
        }

      }

      this.cancelConsumer()
    },

    handleAddConsumer() {
      this.temper = Object.assign({}, defaultRole)
      if (this.$refs.tree) {
        this.$refs.tree.setCheckedNodes([])
      }
      this.dialogType = '0'
      this.dialogVisible = true
    },

    _computeTree(strRoute) {

      this.checkStrictly = true
      let arr = strRoute.split(',')
      arr.forEach(function(value, index, arr) {
        arr[index] = parseInt(value)
      })

      let dpDynamicRoutes = getDynamicRoutes()

      let routes = routerListFun(arr, dpDynamicRoutes)
      // console.log(`编辑:` +JSON.stringify(routes))

      if (routes) {
        this.$nextTick(() => {
          this.$refs['formConsumer'].clearValidate() // 只清除清除验证
          const routes2 = this.generateRoutes(routes)
          console.log(`routes2编辑:` + JSON.stringify(routes2))
          let abs = this.generateArr(routes2)
          console.log(`abs编辑:` + JSON.stringify(abs))
          // this.$refs.tree.setCheckedNodes(abs)
          this.$refs.tree.setCheckedKeys(arr)
          // set checked state of a node not affects its father and child nodes
          this.checkStrictly = false
        })
      }
    },

    handleEdit(scope) {
      this.dialogType = '1'
      this.dialogVisible = true
      this.temper = deepClone(scope.row)

      console.log(`abs编辑:1`)

      // this.checkStrictly = true
      this._computeTree(this.temper.routes)

      // let arr = this.temper.routes.split(',')
      // arr.forEach(function(value, index, arr) {
      //   arr[index] = parseInt(value)
      // })
      //
      // let dpDynamicRoutes = deepClone(dynamicRoutes)
      // this.temper.routes = routerListFun(arr, dpDynamicRoutes)
      //
      // if (this.temper.routes) {
      //   this.$nextTick(() => {
      //     this.$refs['formConsumer'].clearValidate() // 只清除清除验证
      //     const routes = this.generateRoutes(this.temper.routes)
      //     this.$refs.tree.setCheckedNodes(this.generateArr(routes))
      //     // set checked state of a node not affects its father and child nodes
      //     this.checkStrictly = false
      //   })
      // }

    },
    handleDelete({ $index, row }) {
      this.$confirm('确定要删除角色吗?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async() => {
          await deleteConsumer(row.id)
          this.temperList.splice($index, 1)
          this.$message({
            type: 'success',
            message: 'Delete succed !'
          })
        })
        .catch(err => {
          console.error(err)
        })
    },

    async changeAlive(scope, val) {

      await updateConsumer(scope.row.id, scope.row)

      if (scope.row.alive == 0) {
        this.$message({
          showClose: true,
          message: '账号停用',
          type: 'warning'
        })
      } else {
        this.$message({
          showClose: true,
          message: '账号启用',
          type: 'success'
        })
      }

    },

    // Reshape the routes structure so that it looks the same as the sidebar
    generateRoutes(routes, basePath = '/') {
      const res = []

      for (let route of routes) {
        // skip some route
        if (route.hidden) {
          continue
        }

        const onlyOneShowingChild = this.onlyOneShowingChild(route.children, route)

        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild
        }

        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title + '=' + route.id,
          id: route.id

        }

        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path)
        }
        res.push(data)
      }
      return res
    },
    // reference: src/view/layout/components/Sidebar/SidebarItem.vue
    onlyOneShowingChild(children = [], parent) {
      let onlyOneChild = null
      const showingChildren = children.filter(item => !item.hidden)

      // When there is only one child route, the child route is displayed by default
      if (showingChildren.length === 1) {
        onlyOneChild = showingChildren[0]
        onlyOneChild.path = path.resolve(parent.path, onlyOneChild.path)
        return onlyOneChild
      }

      // Show parent if there are no child route to display
      if (showingChildren.length === 0) {
        onlyOneChild = { ...parent, path: '', noShowingChildren: true }
        return onlyOneChild
      }

      return false
    },

    handleSizeChange(val) {
      console.log(`每页 ${val} 条`)
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`)
    },

    handleSelectChange(value) {

      // this.getRoutesArr(value)
      let route = findObjByProp('kcode', value, this.roleList).routes
      this._computeTree(route)
      console.log(`当前角色:` + value + '==route==' + route)

      // let arr = route.split(',')
      // arr.forEach(function(value, index, arr) {
      //   arr[index] = parseInt(value)
      // })
      //
      // let dpDynamicRoutes = deepClone(dynamicRoutes)
      // route = routerListFun(arr, dpDynamicRoutes)
      //
      // if (route) {
      //   this.$nextTick(() => {
      //     this.$refs['formConsumer'].clearValidate() // 只清除清除验证
      //     const routes = this.generateRoutes(route)
      //     this.$refs.tree.setCheckedNodes(this.generateArr(routes))
      //     // set checked state of a node not affects its father and child nodes
      //     this.checkStrictly = false
      //   })
      // }

    },

    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          let temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    }

  }

}
</script>

<style scoped>

.underInputWords {
  font-size: small;
  color: #999 !important;
  padding: 0 5px !important
}

</style>
